﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;
using System.Data;
using System.Data.SqlClient;

using System.Drawing;
using System.Drawing.Imaging;
using System.Text;
using System.Text.RegularExpressions;

using System.Security.Cryptography;
using System.IO;
using System.Configuration;

public partial class register_2 : System.Web.UI.Page
{
    private static string key = "TEST2013";
    public static string DESencode(string str)
    {
        try
        {
            byte[] rgbkey = Encoding.UTF8.GetBytes(key.Substring(0, 8));
            byte[] rgbIV = rgbkey;
            byte[] inputByteArray = Encoding.UTF8.GetBytes(str);
            DESCryptoServiceProvider dCSP = new DESCryptoServiceProvider();
            MemoryStream mstream = new MemoryStream();
            CryptoStream cstream = new CryptoStream(mstream, dCSP.CreateEncryptor(rgbkey, rgbIV), CryptoStreamMode.Write);
            cstream.Write(inputByteArray, 0, inputByteArray.Length);
            cstream.FlushFinalBlock();
            cstream.Close();
            return Convert.ToBase64String(mstream.ToArray());
        }
        catch
        {
            return str;
        }
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["USERNAME"] != null || Session["PASSWORD"] != null)
            Response.Redirect("main.aspx",true);

    }

    public void upload(string path, FileUpload fileupload, string product_id)
    {
        bool fileok = false;
        if (fileupload.HasFile)
        {
            string fileException = System.IO.Path.GetExtension(fileupload.FileName).ToLower();
            string[] allowedException = { ".jpg", ".bmp", ".gif" };
            for (int i = 0; i < allowedException.Length; i++)
            {
                if (fileException == allowedException[i])
                    fileok = true;
            }
        }
        if (fileok)
        {
            if (System.IO.Directory.Exists(path))
            {
            }
            else
            {
                System.IO.Directory.CreateDirectory(path);
            }

            fileupload.SaveAs(path + "\\" + product_id + "_" + fileupload.FileName);
        }
    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        if (TextBox7.Text.Length > 8 || TextBox7.Text.Length < 6)
        {
            Page.RegisterStartupScript("ss", "<script>alert('您输入的密码长度不符合要求!')</script>");
            return;
        }
         SqlConnection sc = new SqlConnection(ConfigurationManager.ConnectionStrings["wbkpt"].ConnectionString.ToString());
            sc.Open();
            string FilePath = "";
            string Image_Path = "";
        bool check = false;
        SqlCommand com_check = new SqlCommand();
        com_check.Connection = sc;
        com_check.CommandText = "select ENTER_ID from INFO_ENTER where ENTER_NAME=@name";
        com_check.Parameters.AddWithValue("@name", TextBox1.Text);
        object temp_check=com_check.ExecuteScalar();

        if ( temp_check== null && TextBox7.Text.Equals(TextBox8.Text) == true)
        {
            check = true;
        }
        else if(temp_check!=null&&TextBox7.Text.Equals(TextBox8.Text) == true)
        {
            check = false;
            label2.Text = "提交失败,用户名已被注册";
        }
        else if (temp_check == null && TextBox7.Text.Equals(TextBox8.Text) == false)
        {
            check = false;
            label2.Text = "提交失败,两次输入的密码不一致";
        }
        else
        {
            check = false;
            label2.Text = "提交失败，请检查两次输入的密码是否一致并试着使用其他用户名注册。";
        }

        if (check == true)
        {

            #region generate new id
            SqlCommand com1 = new SqlCommand();
            com1.Connection = sc;
            com1.CommandText = "select Max(ENTER_ID) from INFO_ENTER";
             while (Application["sqllock"] == "lock")
        {//检测是否已经锁住               
            System.Threading.Thread.Sleep(2000);
        }
        Application["sqllock"] = "lock";//上锁 
       
           
            string max_id = com1.ExecuteScalar().ToString();//获取数据库中最大ID，从10000开始 
            Application["sqllock"] = "unlock";//解锁 
            max_id=max_id.Remove(0, 1);
            int max_id1 = Convert.ToInt32(max_id) + 1;
            string new_id = "E" + max_id1.ToString();//生成的ID
            #endregion
            string qrdecode = string.Empty;
            string wxaccount = string.Empty;
            string carelink = string.Empty;
            //上传图片文件，若没有则跳过
            if (this.FileUpload1.FileName != null && this.FileUpload1.FileName != "")
            {
                if (FileUpload1.PostedFile.ContentLength <= 0)
                {
                    Page.RegisterStartupScript("ss", "<script>alert('上传图片文件为空，请重新选择文件!')</script>");
                    return;
                }
                if (FileUpload1.HasFile)
                {
                    if (FileUpload1.PostedFile.ContentLength > 4196304)
                    {
                        Page.RegisterStartupScript("ss", "<script>alert('文件大小超过4M，请选择更小的图片上传!')</script>");
                        return;
                    }
                    else
                    {
                        FilePath = Server.MapPath("~/QRCODE");
                    }
                    upload(FilePath, this.FileUpload1, new_id);
                    Image_Path = FilePath + "\\" + new_id + "_" + FileUpload1.FileName;
                    //从filename获取用户微信号
                    string ac_tmp = FileUpload1.FileName;
                    ac_tmp = ac_tmp.Remove(0, 11);
                    ac_tmp = ac_tmp.Remove(15, 8);
                    wxaccount = ac_tmp;
                    QRCodeDecoder decoder = new QRCodeDecoder();
                    Bitmap bm = new Bitmap(Image_Path);
                    qrdecode = decoder.decode(new QRCodeBitmapImage(bm));
                    qrdecode = qrdecode.Remove(0, 23);
                    qrdecode = qrdecode.Insert(0, "weixin://qr/");
                    carelink = qrdecode;
                    bm.Dispose();

                }
                else
                {
                    Page.RegisterStartupScript("ss", "<script>alert('所选路径不存在!')</script>");
                    return;
                }
            }
            else
            {
                Page.RegisterStartupScript("ss", "<script>alert('请选择二维码图片并上传！!')</script>");
                return;
            }

            string new_district = DropDownList1.Text;//业务地区

            //TextBox7.text是密码
            string new_field = DropDownList2.Text;            
            string new_size = DropDownList3.Text;
            string new_phone = TextBox6.Text;
            string new_email = TextBox5.Text;
            string new_name = TextBox1.Text;
            string new_type = DropDownList4.Text;

           
           
            //生成邀请码函数
             string ivicode=DESencode(new_id);
            
           
            
            //写入数据库
            SqlCommand com2 = new SqlCommand();
            com2.Connection = sc;
            com2.CommandText = "insert into INFO_ENTER values (@id,@name,@field,@district,@type,@size,@email,@phone,@psw,@wxa,@deg,@carelink,@ivicode,@qq)";
             com2.Parameters.AddWithValue("@id",new_id);
             com2.Parameters.AddWithValue("@name",new_name);
             com2.Parameters.AddWithValue("@field",new_field);
             com2.Parameters.AddWithValue("@district",new_district);
             com2.Parameters.AddWithValue("@type",new_type);
             com2.Parameters.AddWithValue("@size",new_size);
             com2.Parameters.AddWithValue("@email",new_email);
             com2.Parameters.AddWithValue("@phone",new_phone);
             com2.Parameters.AddWithValue("@psw",TextBox7.Text);
             com2.Parameters.AddWithValue("@wxa",wxaccount);
             com2.Parameters.AddWithValue("@deg",0);
             com2.Parameters.AddWithValue("@carelink",carelink);
             com2.Parameters.AddWithValue("@ivicode",ivicode);
             com2.Parameters.AddWithValue("@qq", TextBox9.Text);
             while (Application["sqllock"] == "lock")
        {//检测是否已经锁住               
            System.Threading.Thread.Sleep(2000);
        }
        Application["sqllock"] = "lock";//上锁 


        if (com2.ExecuteNonQuery() == 1)
        {
            Application["sqllock"] = "unlock";//解锁 
            Session["USERNAME"] = TextBox1.Text;
            Session["PASSWORD"] = TextBox7.Text;
            Response.Redirect("register_3.aspx", true);
        }
        else
        {
            Application["sqllock"] = "unlock";//解锁 
            label2.Text = "写入数据库出错，请重试！";
        }

             sc.Close();
        }
      
        
    }
    protected void TextBox1_TextChanged(object sender, EventArgs e)
    {

    }
}